package com.hksj.dpm.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.hksj.base.entity.Properties;
import com.hksj.base.query.AlarmQuery;
import com.hksj.base.query.BaseRecordQuery;
import com.hksj.base.query.BaseSpecialityQuery;
import com.hksj.base.service.DefaultAlarmService;
import com.hksj.base.service.DefaultDeviceService;
import com.hksj.base.vo.AlarmNumVO;
import com.hksj.base.vo.AlarmRecordVO;
import com.hksj.base.vo.DeviceVO;
import com.hksj.common.core.exception.ApplicationException;
import com.hksj.common.core.util.EasyExcelUtil;
import com.hksj.dpm.mapper.DpmMapper;
import com.hksj.dpm.query.DpmAlarmQuery;
import com.hksj.dpm.query.DpmDailyAlarmQuery;
import com.hksj.dpm.query.DpmSpecialityQuery;
import com.hksj.dpm.query.PressureRankQuery;
import com.hksj.dpm.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("dpmDeviceService")
public class DpmService {
    @Autowired
    private DpmMapper dpmMapper;

    @Autowired
    private DefaultDeviceService defaultDeviceService;

    @Autowired
    private DefaultAlarmService defaultAlarmService;

    public AlarmNumVO getAlarmTotalNum(DpmAlarmQuery query) {
        AlarmNumVO res = dpmMapper.getAlarmTotalNum(query);
        return res;
    }

    public List<DpmDailyAlarmNumVO> listDailyAlarmNum(DpmDailyAlarmQuery query) {
        if (query.getDayNum() <= 0){
            throw new ApplicationException("传入的查询天数不正确");
        }
        Date now = new Date();
        DateTime start = DateUtil.beginOfDay(DateUtil.offsetDay(now, 1 - query.getDayNum()));
        String startTimeStr = DateUtil.formatDateTime(start);
        query.setStartTime(startTimeStr);
        query.setEndTime(DateUtil.formatDateTime(now));
        List<DpmDailyAlarmNumVO> list = dpmMapper.listDailyAlarmNum(query);
        Map<String, DpmDailyAlarmNumVO> dailyAlarmNumMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(list)){
            dailyAlarmNumMap = list.stream().collect(Collectors.toMap(DpmDailyAlarmNumVO::getDay, Function.identity()));
        }
        List<DpmDailyAlarmNumVO> res = new ArrayList<>();
        List<DateTime> rangeDayList = DateUtil.rangeToList(start, now, DateField.DAY_OF_MONTH);
        if (!ObjectUtils.isEmpty(rangeDayList)){
            for (DateTime dateTime : rangeDayList) {
                DpmDailyAlarmNumVO dpmDailyAlarmNumVO = dailyAlarmNumMap.get(DateUtil.formatDate(dateTime));
                if (ObjectUtils.isEmpty(dpmDailyAlarmNumVO)){
                    dpmDailyAlarmNumVO = new DpmDailyAlarmNumVO();
                    dpmDailyAlarmNumVO.setDay(DateUtil.formatDate(dateTime));
                }
                res.add(dpmDailyAlarmNumVO);
            }
            list = res;
        }
        return list;
    }

    public List<DpmDeviceStatusVO> listPressureRank(PressureRankQuery query) {
        List<DpmDeviceStatusVO> list = dpmMapper.listDevicePressureRank(query);
        defaultDeviceService.wrapAddr(list);
        return list;
    }

    public CurrentAlarmInfoVO getCurrentAlarmInfo(DpmSpecialityQuery query) {
        CurrentAlarmInfoVO res = dpmMapper.countAlarmNum(query);
        if (ObjectUtils.isEmpty(res)){
            res = new CurrentAlarmInfoVO();
        }
        BaseSpecialityQuery baseSpecialityQuery = new BaseSpecialityQuery();
        BeanUtils.copyProperties(query,baseSpecialityQuery);
        List<AlarmRecordVO> list = defaultAlarmService.listCurrentAlarm(baseSpecialityQuery);
        res.setAlarmList(list);
        return res;
    }

    public void exportAlarm(AlarmQuery query, HttpServletResponse response) {
        query.setDisAblePage(true);
        List<AlarmRecordVO> records = defaultAlarmService.pageAlarmHistory(query).getRecords();
        List<DpmAlarmExportVO> res = new ArrayList<>();
        if (!ObjectUtils.isEmpty(records)){
            for (int i = 0; i < records.size(); i++) {
                AlarmRecordVO alarmRecordVO = records.get(0);
                DpmAlarmExportVO dpmAlarmExportVO = new DpmAlarmExportVO();
                dpmAlarmExportVO.setSortNo(i + 1);
                dpmAlarmExportVO.setAddr(defaultDeviceService.getAddr(alarmRecordVO));
                dpmAlarmExportVO.setDeviceName(alarmRecordVO.getName());
                dpmAlarmExportVO.setValue(alarmRecordVO.getValue());
                dpmAlarmExportVO.setCreateTime(DateUtil.formatDateTime(alarmRecordVO.getCreateTime()));
                res.add(dpmAlarmExportVO);
            }
        }

        String fileName = new StringBuffer()
                .append("压差监测-")
                .append(query.getPushType() == 1 ? "负压" : "正压")
                .append("报警")
                .append(new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date()))
                .toString();
        EasyExcelUtil.exportExcelData(response,fileName,res,DpmAlarmExportVO.class);
    }

    public void exportRecord(BaseRecordQuery query, HttpServletResponse response) {
        query.setDisAblePage(true);
        List<Properties> records = defaultDeviceService.pageRecord(query).getRecords();
        List<DpmExportPressureVO> res = new ArrayList<>();
        if (!ObjectUtils.isEmpty(records)){
            for (int i = 0; i < records.size(); i++) {
                DpmExportPressureVO dpmExportPressureVO = new DpmExportPressureVO();
                dpmExportPressureVO.setSort(i + 1);
                dpmExportPressureVO.setPressure(records.get(i).getValue());
                dpmExportPressureVO.setCreateTime(DateUtil.formatDateTime(records.get(i).getCreateTime()));
                res.add(dpmExportPressureVO);
            }
        }
        DeviceVO deviceInfo = defaultDeviceService.getDeviceInfo(query.getDeviceId());
        defaultDeviceService.wrapAddr(Arrays.asList(deviceInfo));
        String fileName = new StringBuffer()
                .append(deviceInfo.getFloorName())
                .append("_")
                .append(deviceInfo.getRoomName())
                .append("_")
                .append(deviceInfo.getName())
                .append(new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date()))
                .toString();
        EasyExcelUtil.exportExcelData(response,fileName,res,DpmExportPressureVO.class);
    }
}
